#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
char cmd_line[1024];
char* g_argv[1024];
int main()
{
	while(1)
	{
		printf("[root@localhost myshell]# ");
		fflush(stdout);
		memset(cmd_line,'\0',sizeof cmd_line);
		if(fgets(cmd_line, sizeof cmd_line,stdin) == NULL)
		{
			continue;
		}
		cmd_line[strlen(cmd_line)-1] = '\0';
		g_argv[0] = strtok(cmd_line," ");
		int index = 1;
		if(strcmp(g_argv[0],"ls") == 0)
		{
			g_argv[index++] = "--color=auto";
		}
		while(g_argv[index++] = strtok(NULL, " "));
		//for(int i = 0;g_argv[i];i++)
		//{
		//	printf("%s\n",g_argv[i]);
		//}
		//解析完命令行，该要创建子进程了
		if(strcmp(g_argv[0],"cd") == 0)//如果是cd命令，我们不想让子进程执行 不应该创建子进程
		{
			if(g_argv[1] != NULL)
			{
				chdir(g_argv[1]);
			}
		}
		pid_t id = fork();
		if(id == 0)
		{
		//子进程
		printf("下面由子进程进行\n");
		execvp(g_argv[0],g_argv);
		exit(1);
		}
		int status = 0;
		pid_t res = waitpid(-1,&status,0);//阻塞等待
		if(res > 0)//说明等待成功
		{
			printf("等待成功，返回码为：%d\n",WEXITSTATUS(status));
		}
	}
	return 0;
}
